﻿using Sustainalytics.UrlHelpers;
using Sustainalytics.Synchronization.Interface;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ClientDW.Synchronization
{
    public static class EnumerableOfChangedElementExtensions
    {
        public static UrlFriendlyGenerator GetUrlFriendlyGenerator(this IEnumerable<ChangedElement> changedElements, string name)
        {
            if (changedElements == null)
                return null;

            // get changed element corresponding to URL friendly generator
            ChangedElement changedElement = changedElements.Where(ce => ce.AffectedCollection == typeof(UrlFriendlyGenerator).Name).FirstOrDefault();

            if (changedElement == null)
                return null;

            Dictionary<string, object> dic = changedElement.Detail;

            if (dic.TryGetValue("CompanyName", out object value) == false)
            {
                return null;
            }

            var urlFriendlyGenerator = value as UrlFriendlyGenerator;

            return urlFriendlyGenerator;
        }

        public static void AddUrlFriendlyGenerator(this List<ChangedElement> changedElements, string name, UrlFriendlyGenerator generator)
        {
            var changedElement = new ChangedElement
            {
                AffectedCollection = typeof(UrlFriendlyGenerator).Name,
                Detail = new Dictionary<string, object>
                {
                    { "CompanyName", generator }
                }
            };

            changedElements.Add(changedElement);
        }
    }
}